local japi = require "jass.japi"
local jass = require "jass.common"
local storm = require "jass.storm"
local urlenc = require "util.url"
local json = require "util.json"
local load = load
local rsa = require 'util.rsa'
local utility = require 'util.utility'

local function unpack_hotfix(content)
    local ok, res = pcall(urlenc.decode, content)
    if ok and res then 
        local sign = res:match("%-%-0%:([^\r\n]+)")
        local buff = res:match("%-%-%*%-%-(.-)%-%-%*-%-")
        if sign and buff then 
            -- 签名验证通过
            if rsa:check_sign(buff, urlenc.decode(sign)) then
                local result = { }
                -- 地图名字
                result.mapname = res:match("%-%-1:([^\r\n]+)")
                -- 地图版本
                result.version = res:match("%-%-2:([^\r\n]+)")
                -- 补丁版本
                result.replace = res:match("%-%-3:([^\r\n]+)")
                -- 补丁数据
                result.content = res:match("%-%-4:(.-)%-%-5:")

                print(result.mapname)
                print(result.version)
                print(result.replace)
                print(result.content)
                
                -- 判断版本是否对应
                if result.content then 
                    return result
                end 
            else 
                print("热补丁签名错误...", buff, sign)
            end
        end 
    end 
end  

-- 注册同步事件
ac.sync_content:on ("load-client-hotfix") (function (trigger, player, content)
    local hotfix = unpack_hotfix(content)
    if hotfix and hotfix.content then 
        print( hotfix.content )
        local ok, res = pcall(load, hotfix.content)
        if ok and res then 
            ok, res = pcall(res)
            if ok then 
                print("加载热补丁成功...", res)
            else 
                print("加载热补丁失败...", ok, res)
            end
        else 
            print("加载热补丁失败...", ok, res)
        end 
    end 
end)

function ac.load_client_hotfix(path)
    local content = storm.load(path)
    print( "load_client_hotfix", #content)
    if not content then return end;
    ac.sync_content("load-client-hotfix", content)
end 

